const MongoClient = require("mongodb").MongoClient;

let dataBase = () => new Promise((resolve, reject) => {
    const client = new MongoClient('mongodb://localhost:27017', { useNewUrlParser: true });
    client.connect(function(err) {
        if (err) {
            reject(err);
        }
        resolve(client.db('student'));
    });
    client.close();
})

exports.addDB = async function addDB(tableName, queryObj) {

    let tmp = await dataBase();
    let collection = tmp.collection(tableName); //链接数据表
    return new Promise((resolve, reject) => {
        collection.insertMany([queryObj], function(err, result) {
            if (err) {
                reject(err)
            }
            resolve(result)
        });
    })

}

exports.findDB = async function findDB(tableName) {
    let tmp = await dataBase();
    let collection = tmp.collection(tableName); //链接数据表
    return new Promise((resolve, reject) => {
        collection.find({}).toArray(function(err, docs) {
            if (err) {
                reject(err)
            }
            resolve(docs)
        });
    })
}